<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { doPutOrderReceiver, doPutCloseOrderByOrderNo } from '@/apis/order'
import { PAY_TYPE } from '@/apis/paymentDetail/model'
import { useChosseAddress } from '@/hooks/useChooseAddress'
import type { TConfirmAddress } from '@/hooks/useChooseAddress'

// 确认订单页面地址变更
const { orderBtnAddress } = useChosseAddress()
const { offOrderBtnAddress, getOrderBtnAddress } = orderBtnAddress()

const $emit = defineEmits(['cancelOrder'])
const $props = defineProps({ no: { type: String, required: true } })

onUnmounted(() => {
  // 页面卸载移除事件监听
  // uni.$off('chooseAddress', updataOrderReceiver)
  offOrderBtnAddress()
})

const handlePay = () => {
  uni.navigateTo({ url: `/basePackage/pages/pay/Index?no=${$props.no}&orderType=${PAY_TYPE.ORDER}` })
}
/**
 * 导航修改地址
 */
const handelAddress = () => {
  uni.navigateTo({ url: `/basePackage/pages/addressManage/AddressManage?callKey=calltOrderBtn` })
}
// uni.$on('chooseAddress',updataOrderReceiver)
getOrderBtnAddress(updataOrderReceiver)
/**
 * 修改收货地地址
 * @param {*} res
 */
async function updataOrderReceiver(res: TConfirmAddress) {
  const { name, area, address, mobile } = res
  const params = { name, area, address, mobile }
  const { code, msg, data } = await doPutOrderReceiver($props.no, params)
  if (code !== 200) return uni.showToast({ icon: 'none', title: `${msg ? msg : '修改地址失败'}` })
  uni.showToast({ icon: 'none', title: `修改地址成功` })
}

const handleCancelOrder = async () => {
  uni.showModal({
    title: '提示',
    content: '是否需要取消？',
    success: async ({ confirm }) => {
      if (!confirm) return
      const { code, data, msg } = await doPutCloseOrderByOrderNo($props.no)
      if (code !== 200) return uni.showToast({ icon: 'none', title: `${msg ? msg : '取消订单失败'}` })
      uni.showToast({ icon: 'none', title: `订单已取消` })
      $emit('cancelOrder')
    },
  })
}
</script>

<template>
  <view class="btn">
    <view class="btn__primary" @click="handleCancelOrder">取消订单</view>
    <view class="btn__primary" @click="handelAddress">修改地址</view>
    <view class="btn__primary is-tool" @click.stop="handlePay">付款</view>
  </view>
</template>

<style lang="scss" scoped>
@import '@/assets/css/mixins/mixins.scss';
@include b(btn) {
  @include flex(flex-end);
  padding: 30rpx 0;
  @include e(primary) {
    width: 180rpx;
    font-size: 24rpx;
    height: 70rpx;
    line-height: 70rpx;
    text-align: center;
    color: #333;
    border: 1px solid #ccc;
    border-radius: 50rpx;
    margin-left: 10rpx;
  }
  @include when(tool) {
    border-color: #f12f22;
    color: #f12f22;
  }
}
</style>
